<template>
  <div class="movie-detail">
    <!-- 电影封面 -->
    <div class="cover-section">
      <img :src="movie.picPaths" alt="电影封面" class="cover-image" />
      <h1 class="title">{{ movie.title }}</h1>
      <h3>{{ movie.title }} 由：{{ movie.actors }} 等主演,于{{ movie.addedTime }}上映，该影片主要讲解了{{ movie.desc }}</h3>
    </div>

    <!-- 电影信息 -->
    <div class="info-section">
      <component :is="currentInfoContainer">
        <component 
          :is="isMobile ? 'van-cell-group' : 'el-card'" 
          v-for="(value, key) in movie.info" 
          :key="key"
          :class="isMobile ? '' : 'info-card'"
        >
          <component 
            :is="isMobile ? 'van-cell' : 'el-row'" 
            :label="formatLabel(key)"
          >
            <span v-if="isMobile" slot="title">{{ formatLabel(key) }}</span>
            <span>{{ value }}</span>
          </component>
        </component>
      </component>
    </div>

    <!-- 用户评论 -->
    <div class="reviews-section">
      <h2>用户评论</h2>
      
      <!-- 评论列表 -->
      <component :is="currentReviewList" style="margin-top: 10px;">
        <component 
          :is="isMobile ? 'van-card' : 'el-card'" 
          v-for="(review, index) in reviews" 
          :key="index"
          class="review-item"
        >
          <div class="review-content">
            <div class="user-info">
              <span class="username">{{ review.authorName }}</span>
              <!-- <span class="rating">⭐{{ review.rating }}/5</span> -->
            </div>
            <p class="comment">{{ review.body }}</p>
            <div class="review-footer">
              <span class="date">{{ review.addedTime }}</span>
              <component 
                :is="isMobile ? 'van-button' : 'el-button'" 
                size="small" 
                type="primary" 
                @click="replyToReview(index)"
              >回复</component>
            </div>
          </div>
        </component>
      </component>

      <div style="width: 100%;margin-top:20px">
        <el-input
            v-model="comment"
            style="width: 90%;margin-right: 10px;"
            placeholder="说出你的想法..."
            clearable
        /><el-button type="primary" @click="onSubmit">发布</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router'
import { getSingle,TableName,getList,add } from '@/utils/request'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus';

// export default {
//   setup() {
    // 设备检测
    const isMobile = ref(false);
    const route = useRoute()
    const comment=ref('')
    const userStore = useUserStore();
    const user = ref(userStore.getUser)
    // const movieId = ref(route.params.id)
    
    // 电影信息
    const movie = ref({
      title: "星际穿越",
      cover: "https://ts1.tc.mm.bing.net/th/id/R-C.213d5545f3cd624b134baf5b4c0813b1?rik=KCNvuTkhdapelw&riu=http%3a%2f%2fthumb.takefoto.cn%2fwp-content%2fuploads%2f2019%2f02%2f201902160341357015.png&ehk=Zvc72s8KiCId9vm3R%2fv47dLF18vSGWs9tvxORiTQzkc%3d&risl=&pid=ImgRaw&r=0&sres=1&sresct=1",
      info: {
        director: "克里斯托弗·诺兰",
        cast: "马修·麦康纳, 安妮·海瑟薇, 杰西卡·查斯坦",
        releaseDate: "2014-11-07",
        duration: "169分钟",
        genre: "科幻, 冒险, 剧情",
        summary: "地球环境恶化，农作物相继灭绝。前宇航员库珀与一群科学家踏上寻找人类新家园的旅程，在浩瀚宇宙中穿越虫洞，展开一场惊心动魄的太空探险..."
      }
    });
    
    // 用户评论
    const reviews = ref([
      {
        user: { name: "影迷小张", avatar: "https://example.com/avatar1.jpg" },
        rating: 4.5,
        comment: "这是一部震撼人心的科幻巨作！剧情紧凑，特效精美。",
        date: "2023-07-15"
      },
      {
        user: { name: "电影爱好者", avatar: "https://example.com/avatar2.jpg" },
        rating: 4,
        comment: "诺兰再次证明了他作为导演的非凡才华，唯一不足是部分情节略显复杂。",
        date: "2023-07-18"
      }
    ]);
    
    // 新评论
    const newReview = ref({
      user: { name: "" },
      rating: 0,
      comment: ""
    });
    
    // 检测设备类型
    const checkDevice = () => {
      isMobile.value = window.innerWidth < 768;
    };
    
    onMounted(async() => {
      checkDevice();
      const res=await getSingle(route.params.id,TableName.Movies)
      const commentres=await getList(TableName.Comments,route.params.id,'电影')
      console.log(commentres);
      
      movie.value=res
      reviews.value=commentres
      window.addEventListener('resize', checkDevice);
    });
    
    // 提交新评论
    const onSubmit = async() => {
      if(user.value && user.value.id){

        if (comment.value) {
          console.log('提交数据:', comment.value);
          const r=await add({
              articleid: route.params.id,
              body: comment.value,
              userid: user.value.id,
              replyType: '电影',
              typeIndex: TableName.Comments
          })
          console.log(r);
          // 之后应该清空输入框
          comment.value = ''
          ElMessage.success('提交成功！')
          setTimeout(() => {
            window.location.reload()
          }, 1000);
          
        } 
      }else{
        ElMessage.warning('请先登录！')
      }
      
    };
    
    // 回复评论
    const replyToReview = (index) => {
      alert(`正在回复第 ${index + 1} 条评论`);
    };
    
    // 格式化信息标签
    const formatLabel = (key) => {
      const labels = {
        director: "导演",
        cast: "主演",
        releaseDate: "上映日期",
        duration: "时长",
        genre: "类型",
        summary: "简介"
      };
      return labels[key] || key;
    };
    
    // 动态组件选择
    const currentInfoContainer = ref(isMobile.value ? 'van-cell-group' : 'el-row');
    const currentReviewList = ref(isMobile.value ? 'van-list' : 'div');
    
</script>

<style scoped>
.movie-detail {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 封面部分 */
.cover-section {
  text-align: center;
  margin-bottom: 30px;
}

.cover-image {
  width: 100%;
  max-width: 600px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.title {
  margin-top: 20px;
  font-size: 2em;
  color: #333;
}

/* 信息部分 */
.info-section {
  margin-bottom: 40px;
}

.info-card {
  margin-bottom: 20px;
}

/* 评论部分 */
.reviews-section {
  margin-top: 40px;
}

.review-item {
  margin-bottom: 20px;
}

.review-content {
  padding-left: 10px;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.username {
  font-weight: bold;
  font-size: 1.1em;
}

.rating {
  color: #facc14;
}

.comment {
  font-size: 0.95em;
  line-height: 1.6;
  color: #555;
}

.review-footer {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date {
  color: #999;
  font-size: 0.85em;
}

.review-form {
  margin-top: 30px;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
}
</style>